package com.pic.others.utils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class ConnectionFlaskUtils {



   /**
    *
    * @param urlPath :请求路径
    * @param method:请求方式
    * @param key:键
    * @param value：值
    * @return
    */
   public static String getConnectionFlask(
           String urlPath,String method,String key,Object value
   ){
      try {
//         String prefix= "http://192.168.94.117:5000";

         String prefix="http://192.168.137.117:5000";
         urlPath=prefix+urlPath;
         // 创建连接
         URL url = new URL(urlPath);
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setDoOutput(true);
         connection.setDoInput(true);
         connection.setRequestMethod(method);
         connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
         connection.setRequestProperty("Accept", "application/json");
         connection.setRequestProperty("Accept-Encoding", "UTF-8");

         // 构建请求参数
         JSONObject requestParams = new JSONObject();
         // 修改为使用图片 URL 作为输入
         requestParams.put(key, value);

         // 发送请求
         OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
         writer.write(requestParams.toString());
         writer.flush();
         writer.close();

         // 获取响应
         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         String line;
         StringBuilder response = new StringBuilder();
         while ((line = reader.readLine()) != null) {
            response.append(line);
         }
         reader.close();

//         System.out.println(response.toString());
         // 打印响应
//         JSONObject res = JSONObject.parseObject(response.toString());
//         return res;
         return response.toString();

      } catch (Exception e) {
         e.printStackTrace();
      }
      return null;
   }

}
